package com.example.musicplayer.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.musicplayer.R;
import com.example.musicplayer.dao.IMusicHandler;
import com.example.musicplayer.dao.MusicHandler;
import com.example.musicplayer.dto.Song;
import com.example.musicplayer.exception.NoMusicFound;
import com.example.musicplayer.service.MusicServiceStub;


public class SongListActivity extends ListActivity {
	IMusicHandler getMusic;
	List<Song> allMusicList;
	Context context = this;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
		allMusicList = new ArrayList<Song>();
		getMusic = new MusicHandler(getContentResolver(),false, getBaseContext());
		displayMusic();		
		
	}
	//a method thats used to set the content of the listview/helpful to refresh music
	protected void displayMusic() {
		try {
			allMusicList = getMusic.GetMusicList();
		} catch (NoMusicFound e) {
			//opens an alert dialog if no music is found an allows user to purchase more.
			new AlertDialog.Builder(this).setMessage(R.string.no_music).setCancelable(false)
			.setPositiveButton(R.string.buy_music, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										String url = "http://www.example.com";
										Intent i = new Intent(Intent.ACTION_VIEW);
										i.setData(Uri.parse(url));
										startActivity(i);
										}
									}).setNegativeButton(R.string.close_list, new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int id) {
											finish();
																							}
											}).show();
		}
		ArrayAdapter<Song> musicArrayAdapter = new CustomArrayAdapter(SongListActivity.this, R.layout.new_list_item_layout, allMusicList);
		setListAdapter(musicArrayAdapter);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.main_music_player, menu);
		return true;
	}
			@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case(R.id.action_settings):
			startActivity(new Intent(this,MusicPlayerPreferencesActivity.class));
			break;
		case(R.id.refresh):
			//this line makes sure the music is requeryed from storage
			getMusic = new MusicHandler(getContentResolver(),false, getBaseContext());
			displayMusic();
			Toast.makeText(this,R.string.reload, Toast.LENGTH_SHORT).show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
		
		@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// getting listitem index
        int songIndex = position;
        // Starting new intent
        Intent musicServiceIntent = new Intent(this, MusicServiceStub.class);
		musicServiceIntent.setAction(MusicServiceStub.ACTION_SONG_SELECTED);
        // Sending songIndex to SongListActivity
		musicServiceIntent.putExtra("songIndex", songIndex);
        startService(musicServiceIntent);
	}		
	///inner class that defines a custom adapter to use with the listview
	class CustomArrayAdapter extends ArrayAdapter<Song>{
	private Context context;
	private List<Song> objects;

	public CustomArrayAdapter(Context context, int resource, List<Song> objects) {
		super(SongListActivity.this, resource, objects);
		this.context = context;
		this.objects = objects;
		// TODO Auto-generated constructor stub
}
	
	@SuppressWarnings("unchecked")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		//each item in List view, if null creates a new view
		View individualItemView = convertView;
		if(individualItemView == null) {
			//assigns view a reference to layout
			individualItemView = layoutInflater.inflate(R.layout.new_list_item_layout, parent, false);
			//creates viewholder object
			ViewHolder viewHolder = new ViewHolder();
			//assigns each viewholer widget a reference to there widgets in XML
			viewHolder.song = (TextView)individualItemView.findViewById(R.id.song);
			viewHolder.artist = (TextView)individualItemView.findViewById(R.id.artist);
			viewHolder.thumbnail = (ImageView)individualItemView.findViewById(R.id.thumbnail);
			//creates a button and references it with XML/ and declares onclicklistener
			((ImageButton) individualItemView.findViewById(R.id.addSongBtn)).setOnClickListener( new OnClickListener(){
				//when button pressed will add song to playlist
				//commented out for safety
				@Override
				public void onClick(View v) {
					Song song = new Song();
					song = objects.get(getListView().getPositionForView(v));
					getMusic.CreatePlayList(song);
					Toast.makeText(context, song.getSongName() + " song added to playlist", Toast.LENGTH_SHORT).show();
					
				}
				
			});
			individualItemView.setTag(viewHolder);
		}
		final ViewHolder holder = (ViewHolder) individualItemView.getTag();
		//asynctask thats started inorder to load album art on a seperate thread
		//significantly increases list performance
		new AsyncTask<List<Song>, Void, Uri>() {

		    @Override
		    protected Uri doInBackground(List<Song>... params) {
		        Uri albumArtURI = Uri.parse(getMusic.RetrieveAlbumArt(objects.get(position).getAlbumID()));
		        return albumArtURI;
		    }

		    @Override
		    protected void onPostExecute(Uri uri) {
		        super.onPostExecute(uri);
		        holder.thumbnail.setVisibility(View.VISIBLE);
		        holder.thumbnail.setImageURI(uri);
		        }
		    
		}.execute(objects);
		holder.song.setText(objects.get(position).getSongName());
		holder.artist.setText(objects.get(position).getSongArtist());		
		return individualItemView;
	}

}	//view holder class to make listview more efficient
	static class ViewHolder {

		 TextView song;
		 TextView artist;
		 ImageView thumbnail;
	}
}
